package com.example.smartrefreshlayoutdemo.utils;

import androidx.annotation.IdRes;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;

import com.example.smartrefreshlayoutdemo.R;
import com.example.smartrefreshlayoutdemo.fragment.RefreshExampleFragment;
import com.example.smartrefreshlayoutdemo.fragment.RefreshPracticeFragment;
import com.example.smartrefreshlayoutdemo.fragment.RefreshStylesFragment;

public enum TabFragment {
    practice(R.id.navigation_practice, RefreshPracticeFragment.class),
    styles(R.id.navigation_style, RefreshStylesFragment.class),
    examples(R.id.navigation_example, RefreshExampleFragment.class);

    private Fragment fragment;
    public final int menuId;
    private final Class<? extends Fragment> clazz;


    TabFragment(@IdRes int menuId, Class<? extends Fragment> clazz) {
        this.menuId = menuId;
        this.clazz = clazz;
    }

    @NonNull
    public Fragment fragment(){
        if (fragment == null) {
            try {
                fragment = clazz.newInstance();
            } catch (Exception e) {
                e.printStackTrace();
                fragment = new Fragment();
            }
        }
        return fragment;
    }

    public static TabFragment from(int itemId){
        for (TabFragment fragment : values()) {
            if (fragment.menuId == itemId) {
                return fragment;
            }
        }
        return styles;
    }

    public static void onDestroy(){
        for (TabFragment value : values()) {
            value.fragment = null;
        }
    }
}
